import axios from 'axios';
import router from '../router/index';
import { useUserStore } from '../store/UserStore.js';

const _axios = axios.create({
    baseURL:'http://localhost:5000/api',
});

_axios.interceptors.request.use(config => {
    if (!config.url.endsWith('/login')) {
        const token = sessionStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
    }
    return config;
});

// _axios.interceptors.request.use(
//     function(config){
//         if(sessionStorage.getItem('token'))
//             config.headers.Authorization = sessionStorage.getItem('token');
//         return config;
//     },
//     function (error){
//         return Promise.reject(error);
//     }
// )
_axios.interceptors.response.use(
    function (response) {
        if(response.status!=200)
            return response;
        switch(response.data.code){
            case 2000:return response;break;
            case 4001:
            case 4003:
                useUserStore().logout(); //登出（注销）
                // sessionStorage.removeItem('token');
                // sessionStorage.removeItem('user');
                router.push('/login');break;
            case 4000:
            case 5000:
                alert(response.data.msg);break;
            default:alert('出现未知错误，错误码是:'+response.data.code);break;            
        }
        return Promise.reject(response);
    },
    function (error) {
        switch(error.response.status){
            case 404:alert("服务器连接不上，请检查网络或稍后再试");break;
            case 401:alert("服务器要求认证");break
            case 405:alert("服务器请求方式不对，请与开发公司联系");break
            case 500:alert("服务器端错误");break
            default:alert(error);break;            
        }
        return Promise.reject(error);
    }
)
export default _axios